
#!/bin/bash

ips=()
ports=()
cmd=telnet
output=''

showhelp() {
  echo "Usage: `basename $0` -i|--ip=\"ip1 ip2 ...\" -p|--port=\"port1 port2 ...\" [-o file]"
  echo "  -i=|--ip= ip address ( Space-Separated )"
  echo "  -p=|--port= port( Space-Separated )"
  echo "  -o=|--output= output_file; default output to std output"
  echo "  -h show this help"
  echo -e "For example:\n\t `basename $0` --ip=\"10.162.58.33 10.162.224.212\" --port=\"22 80 443\""
  exit 1
}


if [ $# -lt 1 ]; then
  showhelp
fi


for i in "$@"; do
  case $i in
    -i=*|--ip=*)
      ips="${i#*=}"
      shift # past argument=value
      ;;
    -p=*|--port=*)
      ports="${i#*=}"
      shift # past argument=value
      ;;
    -o=*|--output=*)
      output="${i#*=}"
      shift # past argument=value
      ;;
    -v|--verbose)
      verbose=true
      ;;
    -h|--help)
      showhelp
      exit 1
      ;;
    *)
      ;;
  esac
done

echo "************************************************"
echo "ip=$ips"
echo "port=$ports"
echo "output=$output"
echo "verbose=$verbose"
echo "************************************************"


for ip in ${ips[@]}; do
  for port in ${ports[@]};do
    nc -z -w1 ${ip} ${port} 1> /dev/null
    if [ $? -eq 0 ]; then
      isOk='ok'
    else
      isOk='fail'
    fi

    if [ -z ${output} ]; then
      printf "%-20s %-10s %s\n" IP:${ip} PORT:${port} ${isOk}
    else
      printf "%-20s %-10s %s\n" IP:${ip} PORT:${port} ${isOk} >> ${output}
    fi
  done

  if [ -z ${output} ]; then
    echo "************************************************"
  else
    echo "************************************************" >> ${output}
  fi

done
